# -*- coding: utf-8 -*-
#
# File: tfcaTrainingEvent.py
#
# Copyright (c) 2009 by ngi644.net
# Generator: ArchGenXML Version 2.4.1
#            http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#

__author__ = """Takashi NAGAI <nagai@ngi644.net>"""
__docformat__ = 'plaintext'

from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import *
from zope import interface
from zope.interface import implements
import interfaces
from Products.tfcaEvent.interfaces.ITrainingEvent import ITrainingEvent
from Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin

from Products.ATContentTypes.content.event import ATEvent
from Products.ATContentTypes.content.event import ATEventSchema
from Products.tfcaEvent.config import *

##code-section module-header #fill in your manual code here
from Products.CMFCore.utils import getToolByName
##/code-section module-header

schema = Schema((
                 
    TextField(
        name='requirement',
        widget=TextAreaWidget(
            label='Requirement',
            label_msgid='tfcaEvent_label_requirement',
            i18n_domain='tfcaEvent',
        ),
    ),

    IntegerField(
        name='limit',
        widget=IntegerField._properties['widget'](
            label='Limit',
            label_msgid='tfcaEvent_label_limit',
            i18n_domain='tfcaEvent',
        ),
    ),
    DateTimeField(
        name='deadline',
        widget=DateTimeField._properties['widget'](
            label='Deadline',
            label_msgid='tfcaEvent_label_deadline',
            i18n_domain='tfcaEvent',
        ),
    ),
    StringField(
        name='trainingType',
        widget=SelectionWidget(
            label='Trainingtype',
            label_msgid='tfcaEvent_label_trainingType',
            i18n_domain='tfcaEvent',
        ),
        vocabulary='getTrainingTypes',
    ),
    BooleanField(
        name='openForm',
        widget=BooleanField._properties['widget'](
            label='Openform',
            label_msgid='tfcaEvent_label_openForm',
            i18n_domain='tfcaEvent',
        ),
    ),

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

tfcaTrainingEvent_schema = BaseFolderSchema + ATEventSchema.copy() + \
    schema.copy()

##code-section after-schema #fill in your manual code here
tfcaTrainingEvent_schema['attendees'].widget.visible['edit'] = 'invisible'
tfcaTrainingEvent_schema['eventType'].widget.visible['edit'] = 'invisible'
tfcaTrainingEvent_schema['eventUrl'].widget.visible['edit'] = 'invisible'
##/code-section after-schema

class tfcaTrainingEvent(BaseFolder, ATEvent):
    """
    """
    security = ClassSecurityInfo()

    implements(interfaces.ItfcaTrainingEvent, ITrainingEvent)

    meta_type = 'tfcaTrainingEvent'
    _at_rename_after_creation = True

    schema = tfcaTrainingEvent_schema

    ##code-section class-header #fill in your manual code here
    ##/code-section class-header

    # Methods

    security.declarePublic('addParticipant')
    def addParticipant(self):
        """
        """
        pass

    security.declarePublic('delParticipant')
    def delParticipant(self):
        """
        """
        pass
    
    def getEventCategory(self):
        return self.getTrainingType()
    
    
    def getTrainingTypes(self):
        urltool = getToolByName(self, 'portal_url')
        portal = urltool.getPortalObject()
        type_name = portal.getProperty('training_types','')
        
        return DisplayList([(str(x),str(x)) for x in type_name])
    
    

    def get_user_id(self):
        member=self.portal_membership.getAuthenticatedMember()
        return member.getId()
    
    def get_fullname(self):
        member=self.portal_membership.getAuthenticatedMember()
        return member.getProperty('fullname', '')
    

    def chkApply(self):
        now_user = self.get_user_id()
        
        cur_path = '/'.join(self.getPhysicalPath())
        base_query = {}
        base_query['sort_on'] = 'created'
        base_query['path'] = {'query':cur_path, 'depth':1}
        portal_catalog = getToolByName(self, 'portal_catalog')
        results = portal_catalog(base_query)
        for item in results:
            obj = item.getObject()
            if  obj.getUserID() == now_user:
                if obj.getAttendance_record() == '注册':
                    return 'applied'
                elif obj.getAttendance_record() == '取消':
                    return 'canceled'
            else:
                return None
        return None

    def cancel(self):
        """
        cancel Event
        """
        now_user = self.get_user_id()
        
        cur_path = '/'.join(self.getPhysicalPath())
        base_query = {}
        base_query['sort_on'] = 'created'
        base_query['path'] = {'query':cur_path, 'depth':1}
        base_query['Creator'] = now_user
        portal_catalog = getToolByName(self, 'portal_catalog')
        results = portal_catalog(base_query)
        retFlag = False
        for item in results:
            obj = item.getObject()
            if obj.getAttendance_record() == '注册':
                obj.setAttendance_record('取消')
                # indexing
                obj.indexObject()
                retFlag = True
        return_url = self.absolute_url()
        return self.REQUEST.RESPONSE.redirect(return_url)

    
    def apply(self):
        """
        add Participant
        """
        from DateTime import DateTime
        current_date = DateTime()
        ###import pdb
        ###pdb.set_trace()
        # create new Participantobject
        urltool = getToolByName(self, 'portal_url')
        portal = urltool.getPortalObject()
        id = self.generateUniqueId()
        new_id = self.invokeFactory(id=id, type_name='Participant')
        if new_id is None or new_id == '':
           new_id = id 
        # get new Participant Object
        participant = self[id]
        
        if self.get_user_id():
            participant.setUserID(self.get_user_id())
        if self.get_fullname():
            participant.setTitle(self.get_fullname())
        else:
            participant.setTitle(self.get_user_id())
        
        if self.REQUEST.form.get("comment"):
            vComment=self.REQUEST.form["comment"]
            participant.setComment(vComment)
        participant.setApplyDate(current_date)
        
        # indexing
        participant.indexObject()
        
        return_url = self.absolute_url()
        return self.REQUEST.RESPONSE.redirect(return_url)


registerType(tfcaTrainingEvent, PROJECTNAME)
# end of class tfcaTrainingEvent

##code-section module-footer #fill in your manual code here
##/code-section module-footer



